// 微前端路由管理器
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

// 动态导入模块配置
const moduleConfigs = []

// 从 modules 目录动态加载模块配置
const modulesContext = import.meta.glob('../modules/*/module.config.js')

Object.keys(modulesContext).forEach(async (path) => {
  try {
    const moduleConfig = await modulesContext[path]()
    moduleConfigs.push(moduleConfig)
  } catch (error) {
    console.warn('Failed to load module config:', path, error)
  }
})

class MicroFrontendRouter {
  constructor() {
    this.routes = []
    this.modules = new Map()
    this.router = null
    this.initialized = false
  }

  /**
   * 注册模块路由
   * @param {string} moduleName - 模块名称
   * @param {Object} routeConfig - 路由配置
   */
  registerRoute(moduleName, routeConfig) {
    const route = {
      path: routeConfig.path,
      name: routeConfig.name || moduleName,
      component: routeConfig.component,
      meta: {
        ...routeConfig.meta,
        moduleName,
        title: routeConfig.meta?.title || moduleName,
        layout: routeConfig.meta?.layout || 'default',
        theme: routeConfig.meta?.theme || 'default',
        permissions: routeConfig.meta?.permissions || []
      },
      children: routeConfig.children || []
    }

    this.routes.push(route)
    this.modules.set(moduleName, route)
  }

  /**
   * 批量注册模块路由
   * @param {Array} moduleRoutes - 模块路由配置数组
   */
  registerRoutes(moduleRoutes) {
    moduleRoutes.forEach(route => {
      this.registerRoute(route.moduleName, route.config)
    })
  }

  /**
   * 动态加载模块路由
   */
  async loadModuleRoutes() {
    // 等待所有模块配置加载完成
    await Promise.allSettled(
      Object.keys(modulesContext).map(path => modulesContext[path]())
    )

    // 注册所有模块路由
    for (const config of moduleConfigs) {
      if (config && config.default) {
        const routeConfig = config.default
        this.registerRoute(routeConfig.name, routeConfig)
      }
    }
  }

  /**
   * 初始化路由
   */
  async initialize() {
    if (this.initialized) return

    // 加载模块路由配置
    await this.loadModuleRoutes()

    // 添加默认路由（首页）
    const defaultRoutes = [
      {
        path: '/',
        name: 'home',
        component: HomeView,
        meta: {
          title: 'Page Factory - Micro Frontend Platform',
          layout: 'home',
          theme: 'default'
        }
      }
    ]

    // 合并所有路由
    const allRoutes = [...defaultRoutes, ...this.routes]

    // 创建Vue Router实例
    this.router = createRouter({
      history: createWebHistory(import.meta.env.BASE_URL),
      routes: allRoutes
    })

    // 添加路由守卫
    this.setupGuards()

    this.initialized = true
    console.log('MicroFrontendRouter initialized with', allRoutes.length, 'routes')
  }

  /**
   * 设置路由守卫
   */
  setupGuards() {
    this.router.beforeEach(async (to, from, next) => {
      console.log(`Navigating from ${from.name || 'unknown'} to ${to.name}`)

      // 路由切换前的处理 - 切换主题
      if (to.meta?.theme && from.meta?.theme !== to.meta.theme) {
        try {
          // 等待主题切换完成
          await import('../assets/styles/micro-frontend.css')
          document.body.className = document.body.className.replace(/theme-\S+/g, '')
          document.body.classList.add(`theme-${to.meta.theme}`)

          // 更新CSS变量
          const themeVariables = this.getThemeVariables(to.meta.theme)
          Object.keys(themeVariables).forEach(key => {
            document.documentElement.style.setProperty(`--${key}`, themeVariables[key])
          })
        } catch (error) {
          console.warn('Theme switching failed:', error)
        }
      }

      next()
    })

    this.router.afterEach((to) => {
      // 路由切换后的处理
      if (to.meta?.title) {
        document.title = to.meta.title
      }
    })
  }

  /**
   * 获取主题变量
   */
  getThemeVariables(themeName) {
    const themes = {
      'default': {
        primary: '#42b883',
        secondary: '#35495e',
        background: '#ffffff',
        surface: '#f5f5f5',
        text: '#333333',
        'on-primary': '#ffffff',
        'on-secondary': '#ffffff',
        'on-background': '#333333',
        'on-surface': '#333333'
      },
      'ai-naming': {
        primary: '#6a11cb',
        secondary: '#2575fc',
        background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
        surface: '#ffffff',
        text: '#2d3748',
        'on-primary': '#ffffff',
        'on-secondary': '#ffffff',
        'on-background': '#2d3748',
        'on-surface': '#4a5568'
      },
      'office-pdf': {
        primary: '#1e3a8a',
        secondary: '#3b82f6',
        background: '#f8fafc',
        surface: '#ffffff',
        text: '#1f2937',
        'on-primary': '#ffffff',
        'on-secondary': '#ffffff',
        'on-background': '#1f2937',
        'on-surface': '#374151'
      },
      'ai-bot': {
        primary: '#ec4899',
        secondary: '#8b5cf6',
        background: 'linear-gradient(135deg, #1e1b4b 0%, #3730a3 100%)',
        surface: '#3730a3',
        text: '#f3e8ff',
        'on-primary': '#ffffff',
        'on-secondary': '#ffffff',
        'on-background': '#f3e8ff',
        'on-surface': '#e9d5ff'
      }
    }

    return themes[themeName] || themes['default']
  }

  /**
   * 获取路由实例
   */
  getRouter() {
    if (!this.initialized) {
      this.initialize()
    }
    return this.router
  }

  /**
   * 获取所有路由
   */
  getRoutes() {
    return this.routes
  }

  /**
   * 获取模块路由
   * @param {string} moduleName - 模块名称
   */
  getModuleRoute(moduleName) {
    return this.modules.get(moduleName)
  }

  /**
   * 动态添加路由
   * @param {string} moduleName - 模块名称
   * @param {Object} routeConfig - 路由配置
   */
  addRoute(moduleName, routeConfig) {
    this.registerRoute(moduleName, routeConfig)
    if (this.router) {
      this.router.addRoute(routeConfig)
    }
  }

  /**
   * 删除路由
   * @param {string} moduleName - 模块名称
   */
  removeRoute(moduleName) {
    const route = this.modules.get(moduleName)
    if (route) {
      this.modules.delete(moduleName)
      const index = this.routes.indexOf(route)
      if (index > -1) {
        this.routes.splice(index, 1)
      }
      console.log(`Route for module '${moduleName}' removed`)
    }
  }
}

// 创建路由实例
const microFrontendRouter = new MicroFrontendRouter()

export default microFrontendRouter
export { MicroFrontendRouter }